<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
       /*
            参数：url、请求参数data/params、方式、设置请求头、拿到数据的回调函数、未拿到数据的函数
        */

        getAjax({
            url: "http://www.bufantec.com/api/douban/movie/in_theaters",
            data: {
                start: 2
            },
            // success(res) {
            //     console.log('这是我设置的', res);
            // },
        })

        getAjax({
            url: 'http://bufantec.com/api/test/user/save',
            type: 'POST',
            header: 'application/x-www-form-urlencoded',
            data: {
                name: "李白", // 昵称
                age: 14,
                sex: 0,
                tel: 12346578,
                address: "长安城东北角",
                school: "长安吟诗学院",
                username: "71", // 登录名
                password: 123456
            },
            success(res) {
                console.log('这是我设置的', JSON.parse(res));
            },
            fail() {
                console.log('这是我设置的失败函数');
            }
        })

        function getAjax(obj) {
            if (!obj.url) {
                console.log('请求地址没写');
                return
            }
            var xhr = new XMLHttpRequest();
            // 默认参数
            obj = Object.assign({
                type: 'GET',
                data: null,
                header: null,
                success(res) {
                    console.log(JSON.parse(res));
                },
                fail(){
                    console.log('你失败了');
                }
            }, obj);
            xhr.onload = function () {
                obj.success(xhr.responseText)
            }

            xhr.onerror = function () {
                obj.fail()
            }
            //参数序列化
            if (obj.data) {
                var str = '';
                for (const j in obj.data) {
                    str += '&' + j + '=' + obj.data[j]
                }
                str = str.slice(1);
            }

            if (obj.type.toUpperCase() == 'GET') {
                console.log(str);
                xhr.open(obj.type, obj.url + '?' + str);
                xhr.send(null)
            } else {
                xhr.open(obj.type, obj.url);
                xhr.setRequestHeader('content-type', obj.header);
                xhr.send(str);
            }
        }
    </script>
</body>
</html>